import osproc, streams, tables, strutils
import config, util

let
  (cmrOutput, cmrErrorCode) = execCmdEx("cmus-remote -Q", {poUsePath})

if cmrErrorCode != 0:
  echo statusChar["notRunning"]
  quit 0

var
  cmrLines: RefLines
  lineBuffer, title, artist, statusBody, statusPrefix, statusSuffix: string
  splitBuffer: (string, string)
  percentage: int

new(cmrLines)

for line in cmrOutput.split("\n"):
  echo line
  lineBuffer = $line
  removePrefix lineBuffer, "set"
  removePrefix lineBuffer, "tag"
  # lineBuffer = lineBuffer.strip(trailing = false, chars = "set")
  # lineBuffer = lineBuffer.strip(trailing = false, chars = "tag")
  lineBuffer = lineBuffer.strip
  splitBuffer = lineBuffer.splitFirst
  echo splitBuffer
  cmrLines[splitBuffer[0]] = splitBuffer[1]

if cmrLines["status"] == "stopped":
  echo statusChar["stopped"]
  quit 0
  
title.trySet cmrLines, "title", defaultTitle
artist.trySet cmrLines, "artist", defaultArtist

if showProgress:
   percentage = toInt parseInt(cmrLines["position"]) / parseInt(cmrLines["duration"]) * 100

if stripAfterTitle:
  for c in stripAfterChars:
    if c.len == 1: title.stripUntil(c[0])
    else: title.stripUntil(c)
  title = title.strip

statusPrefix.add statusChar[cmrLines["status"]]
statusPrefix.condAdd showProgress, ' ' & $percentage & '%'

statusBody.add artist & " - " & title


if statusBody.len > outputLengthCap and outputLengthCap != 0:
  statusBody = statusBody[0..outputLengthCap - 1] & cutoffString

if showStatusChars:
  statusSuffix.add "["
  statusSuffix.condAdd parseBool(cmrLines["continue"]), "C"
  statusSuffix.condAdd parseBool(cmrLines["repeat"]), "R"
  statusSuffix.condAdd parseBool(cmrLines["shuffle"]), "S"
  statusSuffix.add "]"

statusSuffix = statusSuffix.strip
statusPrefix = statusPrefix.strip

echo statusPrefix & ' ' & statusBody & ' ' & statusSuffix
quit 0
